<template>
  <div class="site-wrapper site-page--login">
    <div class="site-content__wrapper">
      <div class="site-content">
        <div class="brand-info">
          <h2 class="brand-info__text">后台管理系统</h2>
          <p class="brand-info__intro">基于SpringCloud+vue全家桶编写的前后端分离博客项目</p>
          <p class="brand-info__intro">简约风格，功能完善，具备完备的后台管理和前端数据展示</p>
        </div>
        <div class="login-main">
          <el-tabs v-model="loginType" @tab-click="handleClick">
            <el-tab-pane label="账号密码登录" name="accountLogin">
              <el-form :model="userDataForm" :rules="userDataRule" ref="userDataForm" @keyup.enter.native="dataFormSubmit()" status-icon>
                <el-form-item prop="userName">
                  <el-input v-model="userDataForm.userName" placeholder="用户名或手机号">
                    <template slot="prefix">
                      <i class="el-icon-user"></i>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input v-model="userDataForm.password" type="password" placeholder="密码">
                    <template slot="prefix">
                      <i class="el-icon-lock"></i>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="captcha">
                  <el-row :gutter="20">
                    <el-col :span="14">
                      <el-input v-model="userDataForm.captcha" placeholder="验证码">
                        <template slot="prefix">
                          <i class="el-icon-mobile-phone"></i>
                        </template>
                      </el-input>
                    </el-col>
                    <el-col :span="10" class="login-captcha">
                      <img :src="captchaPath" @click="getCaptcha()" alt="">
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item>
                  <el-checkbox v-model="rememberMe" v-if="showRememberMe">记住我</el-checkbox>
                </el-form-item>
                <el-form-item>
                  <el-button class="login-btn-submit" type="primary" @click.native.prevent="dataFormSubmit()" :loading="userLoading">登录</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="手机号码登录" name="phoneLogin">
              <el-form :model="phoneDataForm" :rules="phoneDataRule" ref="phoneDataForm" @keyup.enter.native="phoneFormSubmit()" status-icon>
                <el-form-item prop="phone">
                  <el-input v-model="phoneDataForm.phone" placeholder="手机号码">
                    <template slot="prefix">
                      <i class="el-icon-phone"></i>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="code">
                  <el-row :gutter="20">
                    <el-col :span="14">
                      <el-input v-model="phoneDataForm.code" placeholder="验证码">
                        <template slot="prefix">
                          <i class="el-icon-mobile-phone"></i>
                        </template>
                      </el-input>
                    </el-col>
                    <el-col :span="10" class="login-captcha" >
                      <el-button type="primary" @click="getPhoneCode" :disabled="countdown > 0">{{ countdown > 0 ? `${countdown}秒后重新获取` : '获取短信验证码' }}</el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item>
                  <el-checkbox v-model="rememberMe" v-if="showRememberMe">记住我</el-checkbox>
                </el-form-item>

                <el-form-item>

                  <el-button class="login-btn-submit" type="primary" @click.native.prevent="phoneFormSubmit()" :loading="phoneLoading">登录</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>


        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getUUID } from '@/utils';
import { phoneCode } from "@/api/user";
import { getAesKeyAndIv,
  getCaptcha,
  getRole,
  login,
  phoneLogin } from "@/api/auth";
import { uuid } from "mockjs/src/mock/random/misc";
import { setAllLoginInfo,
  setUserRole,
  setPermission } from "@/utils/userToken";
import { encrypt } from "@/utils/secret";
import { LOGIN_PHONE_CODE_TYPE, PHONE_CODE_COUNT_DOWN_TIME } from "@/utils/constants";
import { getUserPermissionCodeList } from "@/api/permission";
import { getStorageUserName,
  getStoragePassword,
  setStoragePassword,
  setStorageUserName } from "@/utils/rememberMe";
import { getUserInfo } from "@/api/user";

export default {
  data () {
    return {
      rememberMe: false,
      userDataForm: {
        userName: '',
        password: '',
        uuid: '',
        captcha: ''
      },
      countdown: 0,
      phoneDataForm: {
        phone: "",
        code: ""
      },
      captchaPath: '',
      userLoading: false,
      phoneLoading: false,
      phoneDesc: "获取验证码",
      aesKey: "63eeac68cf074c8c",
      aesIv: "63eeac68cf074c8c",
      noEncryptPwd: '',
      loginType: 'accountLogin',
      showRememberMe: true,
      userDataRule: {
        userName: [
          { required: true, message: '帐号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      },
      phoneDataRule: {
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    this.getCaptcha();
    this.getAesKeyIv();
    this.getLocalStorageUserInfo();
  },

  methods: {
    getAesKeyIv() {
      getAesKeyAndIv().then(res => {
        if (res.code === 200) {
          this.aesKey = res.data.key
          this.aesIv = res.data.iv
        }
      })
    },

    // 获取短信验证码
    getPhoneCode() {
      if (!this.phoneDataForm.phone) {
        this.$notify({
          title: '成功',
          message: '请输入手机号码',
          type: 'success',
          duration: 1500
        });
        return;
      }

      if (this.phoneDataForm.phone.length !== 11) {
        this.$notify({
          title: '成功',
          message: '手机号码不合法',
          type: 'success',
          duration: 1500
        });
        return;
      }

      if (this.countdown > 0) {
        return;
      }
      this.countdown = PHONE_CODE_COUNT_DOWN_TIME;
      phoneCode(this.phoneDataForm.phone, LOGIN_PHONE_CODE_TYPE).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '验证码发送成功',
            type: 'success',
            duration: 1500
          });
          const intervalId = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown -= 1;
            } else {
              clearInterval(intervalId);
            }
          }, 1000);
        } else {
          this.$notify({
            title: '失败',
            message: res.message,
            type: 'success',
            duration: 1500
          });
          this.countdown = 0;
        }
      }).catch(err => {
        this.countdown = 0;
      })

    },

    // 手机验证码登录
    phoneFormSubmit() {
      if (this.phoneDataForm.code.length !== 6) {
        this.$message.error('验证码非法');
        this.phoneDataForm.code = '';
        return;
      }
      this.$refs['phoneDataForm'].validate((valid) => {
        if (valid) {
          this.phoneLoading = true;
          phoneLogin(this.phoneDataForm).then(res => {
            if (res.code === 200) {
              const data = res.data;
              this.userLoginSuccess(data.tokenValue, data.loginId);
            } else if (res.code === 302 || res.code === 315 || res.code === 319) {
              this.phoneLoading = false;
              this.$message.error(res.message);
              this.phoneDataForm.code = '';
            } else {
              this.phoneDataForm = {}
              this.phoneLoading = false;
              this.$message.error(res.message);
            }
          }).catch(err => {
            this.phoneDataForm = {}
            this.phoneLoading = false;
            this.$message.error("系统异常!");
          })
        }
      })
    },

    // 用户名密码登录
    dataFormSubmit () {
      this.noEncryptPwd = this.userDataForm.password;
      this.userDataForm.password = encrypt(this.userDataForm.password, this.aesKey, this.aesIv);
      this.$refs['userDataForm'].validate((valid) => {
        if (valid) {
          if (this.userDataForm.captcha.length !== 5) {
            this.$message.error('验证码非法');
            this.userDataForm.captcha = '';
            this.userDataForm.password = '';
            return;
          }
          this.userLoading = true;
          login(this.userDataForm).then(res => {
            // 登录成功
            if (res.code === 200) {
              const data = res.data;
              if (this.rememberMe) {
                this.doRememberMe();
              }
              this.userLoginSuccess(data.tokenValue, data.loginId);
            } else if (res.code === 302 || res.code === 315 || res.code === 319) {
              // 验证码非法或已过期 用户锁定等
              this.$message.error(res.message);
              this.userDataForm.captcha = '';
              this.userDataForm.password = '';
              this.getCaptcha();
              this.userLoading = false;
            } else {
              // 登录失败
              this.userDataForm = {}
              this.userLoading = false;
              this.getCaptcha();
              this.$message.error('登录失败，请联系管理员!');
            }
          }).catch(err => {
            this.userDataForm = {}
            this.userLoading = false;
            this.getCaptcha();
            this.$message.error("系统异常!");
          })

        }
      })
    },

    // 登录成功之后执行的操作
    userLoginSuccess(token, userId) {
      setAllLoginInfo(token, userId);
      this.getUserDetailInfo(userId);
      this.getUserRole(userId);
      this.getUserPermission(userId);
      this.userLoading = false;
      this.$message.success('登录成功！');
      this.$router.replace('/charts');
    },

    getUserDetailInfo(userId) {
      getUserInfo(userId).then(res => {
        if (res.code === 200) {
          this.$store.commit('updateUserName', res.data.userName);
          this.$store.commit('updateUserAvatar', res.data.avatar);
        }
      })
    },

    // 获取localstorage中存储的用户登录信息
    getLocalStorageUserInfo() {
      let userName = getStorageUserName();
      let password = getStoragePassword();
      if (!userName || !password) {
        return;
      }

      this.userDataForm.userName = userName;
      this.userDataForm.password = password;

    },

    // 记住我
    doRememberMe() {
      setStorageUserName(this.userDataForm.userName);
      setStoragePassword(this.noEncryptPwd);
    },

    // 获取验证码
    getCaptcha () {
      this.userDataForm.uuid = getUUID();
      getCaptcha(this.userDataForm.uuid).then(res => {
        this.captchaPath = "data:image/jpeg;base64," +
          btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
      })
    },

    // 获取用户角色
    getUserRole(userId) {
      getRole(userId).then(res => {
        if (res.code === 200) {
          setUserRole(res.data.roleCode);
        }
      })
    },

    // 获取用户权限
    getUserPermission(userId) {
      getUserPermissionCodeList(userId).then(res => {
        if (res.code === 200) {
          setPermission(res.data);
          console.log('当前登录用户的权限：', JSON.stringify(res.data))
        }
      })
    },

    // 切换登录方式
    handleClick(tab, event) {
      let loginType = tab.name;
      if (loginType === 'phoneLogin') {
        this.showRememberMe = false;
      } else {
        this.showRememberMe = true;
      }
    },

  }
}
</script>

<style lang="scss">
.site-wrapper.site-page--login {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(38, 50, 56, .6);
  overflow: hidden;
  &:before {
    position: fixed;
    top: 0;
    left: 0;
    z-index: -1;
    width: 100%;
    height: 100%;
    content: "";
    background-image: url(../../assets/background.jpg);
    background-size: cover;
  }
  .site-content__wrapper {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 0;
    margin: 0;
    overflow-x: hidden;
    overflow-y: auto;
    background-color: transparent;
  }
  .site-content {
    min-height: 100%;
    padding: 30px 500px 30px 30px;
  }
  .brand-info {
    margin: 220px 100px 0 90px;
    color: #fff;
  }
  .brand-info__text {
    margin:  0 0 22px 0;
    font-size: 48px;
    font-weight: 400;
    text-transform : uppercase;
  }
  .brand-info__intro {
    margin: 10px 0;
    font-size: 16px;
    line-height: 1.58;
    opacity: .6;
  }
  .login-main {
    position: absolute;
    top: 0;
    right: 0;
    padding: 150px 60px 180px;
    width: 500px;
    min-height: 100%;
    background-color: #fff;
  }
  .login-title {
    font-size: 16px;
    text-align: center;
  }
  .login-captcha {
    overflow: hidden;
    > img {
      width: 100%;
      cursor: pointer;
    };

  }
  .login-btn-submit {
    width: 100%;
    margin-top: -2px;
  }
}
</style>
